package com.qd.system.service.log;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.db.BaseService;
import com.cdqidi.exception.ApiException;
import com.qd.common.sys.domain.entity.log.DataLogDTO;
import com.qd.system.mapper.DataLogMapper;
import com.qd.system.model.DataLog;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 数据日志
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class DataLogService extends BaseService<DataLogMapper, DataLog> {

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public DataLogDTO save(DataLogDTO dto) {
        final DataLog model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<DataLog> mList) {
        if (!super.saveBatch(mList)) {
            throw new ApiException("批量添加失败");
        }
    }

    /**
     * 删除，单个
     *
     * @param logId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String logId) {
        final DataLog model = Optional.ofNullable(getById(logId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(logId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        checkIds(ids);
        if (!super.removeByIds(ids)) {
            throw new ApiException("批量删除失败");
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(DataLogDTO dto) {
        final QueryWrapper<DataLog> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param logId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String logId) {
        boolean exists = false;
        if (StringUtils.hasLength(logId)) {
            final DataLog model = getById(logId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param logId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public DataLog getById(String logId) {
        return super.getById(logId);
    }

    /**
     * 根据主键获取数据
     *
     * @param logId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public DataLogDTO getByIdDto(String logId) {
        return Optional.ofNullable(getById(logId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public DataLog getOne(DataLogDTO dto) {
        final QueryWrapper<DataLog> queryWrapper = createQueryWrapper(dto);
        DataLog model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public DataLogDTO getOneDto(DataLogDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<DataLog> getList(DataLogDTO dto) {
        final QueryWrapper<DataLog> queryWrapper = createQueryWrapper(dto);
        final List<DataLog> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<DataLogDTO> getListDto(DataLogDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<DataLogDTO> page(Page<DataLog> page, DataLogDTO dto) {
        final QueryWrapper<DataLog> queryWrapper = createQueryWrapper(dto, "t1.");
        final IPage<DataLogDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public DataLogDTO modelToDto(DataLog model) {
        if (null == model) {
            return null;
        }
        final DataLogDTO dto = new DataLogDTO();
        dto.setLogId(model.getLogId());
        dto.setUserId(model.getUserId());
        dto.setUserName(model.getUserName());
        dto.setUserIp(model.getUserIp());
        dto.setTitle(model.getTitle());
        dto.setMethod(model.getMethod());
        dto.setRemote(model.getRemote());
        dto.setRequestMethod(model.getRequestMethod());
        dto.setOperatorType(model.getOperatorType());
        dto.setOrgName(model.getOrgName());
        dto.setUrl(model.getUrl());
        dto.setRawSql(model.getRawSql());
        dto.setTableName(model.getTableName());
        dto.setContent(model.getContent());
        dto.setHistoryContent(model.getHistoryContent());
        dto.setDaoMethodName(model.getDaoMethodName());
        dto.setSqlReturnId(model.getSqlReturnId());
        dto.setOperatorTime(model.getOperatorTime());
        dto.setSqlCommandType(model.getSqlCommandType());
        dto.setOrgId(model.getOrgId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public DataLog dtoToModel(DataLogDTO dto) {
        if (null == dto) {
            return null;
        }
        final DataLog model = new DataLog();
        model.setLogId(dto.getLogId());
        model.setUserId(dto.getUserId());
        model.setUserName(dto.getUserName());
        model.setUserIp(dto.getUserIp());
        model.setTitle(dto.getTitle());
        model.setMethod(dto.getMethod());
        model.setRemote(dto.getRemote());
        model.setRequestMethod(dto.getRequestMethod());
        model.setOperatorType(dto.getOperatorType());
        model.setOrgName(dto.getOrgName());
        model.setUrl(dto.getUrl());
        model.setRawSql(dto.getRawSql());
        model.setTableName(dto.getTableName());
        model.setContent(dto.getContent());
        model.setHistoryContent(dto.getHistoryContent());
        model.setDaoMethodName(dto.getDaoMethodName());
        model.setSqlReturnId(dto.getSqlReturnId());
        model.setOperatorTime(dto.getOperatorTime());
        model.setSqlCommandType(dto.getSqlCommandType());
        model.setOrgId(dto.getOrgId());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(DataLogDTO dto) {
        dto.setOperatorTypeDisplay(MbUtil.idToDisplay(dto.getOperatorType()));
        dto.setRemoteDisplay(MbUtil.idToDisplay(dto.getRemote()));

    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<DataLogDTO> modelToDtoList(List<DataLog> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<DataLog> dtoToModelList(List<DataLogDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<DataLog> createQueryWrapper(DataLogDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<DataLog> createQueryWrapper(DataLogDTO dto, String tableAlias) {
        final QueryWrapper<DataLog> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
            if (StringUtils.hasLength(dto.getUserName())) {
                queryWrapper.like(tableAlias + "user_name", dto.getUserName());
            }
            if (StringUtils.hasLength(dto.getTitle())) {
                queryWrapper.eq(tableAlias + "title", dto.getTitle());
            }
            if (StringUtils.hasLength(dto.getMethod())) {
                queryWrapper.like(tableAlias + "method", dto.getMethod());
            }
            if (StringUtils.hasLength(dto.getRemote())) {
                queryWrapper.eq(tableAlias + "remote", dto.getRemote());
            }
            if (StringUtils.hasLength(dto.getRequestMethod())) {
                queryWrapper.eq(tableAlias + "request_method", dto.getRequestMethod());
            }
            if (StringUtils.hasLength(dto.getOperatorType())) {
                queryWrapper.eq(tableAlias + "operator_type", dto.getOperatorType());
            }
            if (StringUtils.hasLength(dto.getOrgName())) {
                queryWrapper.like(tableAlias + "org_name", dto.getOrgName());
            }
            if (StringUtils.hasLength(dto.getTableName())) {
                queryWrapper.eq(tableAlias + "table_name", dto.getTableName());
            }
            if (StringUtils.hasLength(dto.getDaoMethodName())) {
                queryWrapper.eq(tableAlias + "dao_method_name", dto.getDaoMethodName());
            }
            if (StringUtils.hasLength(dto.getSqlCommandType())) {
                queryWrapper.eq(tableAlias + "sql_command_type", dto.getSqlCommandType());
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + "org_id", dto.getOrgId());
            }
            if (StringUtils.hasLength(dto.getBeginTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "operator_time,'%Y-%m-%d') >= {0}", dto.getBeginTime());
            }
            if (StringUtils.hasLength(dto.getEndTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "operator_time,'%Y-%m-%d') <= {0}", dto.getEndTime());
            }
        }
        queryWrapper.orderByDesc(tableAlias + "operator_time");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public void checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<DataLog> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return;
        }
        List<String> dbIds = list.stream().map(DataLog::getLogId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
    }

}